# -*- coding: utf-8 -*-

"""
controller base
"""

import tornado.web
import json

class Controller(tornado.web.RequestHandler):
    """
    base control
    """
    isAjax = 0

    def __init__(self, application, request, **kwargs):
        """class init call the parent init"""
        super(Controller, self).__init__(application, request, **kwargs)
        self.isAjax = bool(super(Controller, self).get_argument("isAjax", 0))

    def get(self):
        """default handler"""
        self.write_error(404)

    def post(self):
        """default post handler"""
        self.write_error(404)

    def write_error(self, status_code, **kwargs):
        if status_code == 404:
            self.render('error/404.html')
            # self.write('404')
        elif status_code == 500:
            self.render('error/500.html')
            # self.write('500')
        else:
            self.render('error/err.html', code=status_code, msg=kwargs['msg'])
            # self.write('error:%s' % status_code)

    def data_received(self, chunk):
        """im base class method"""
        print chunk

    def on_finish(self):
        """im base class method of print handler class"""
        # print self.request
        print 'called:', self.__class__

    def ajax_out(self, **kwargs):
        """
        :param kwargs: 
        :return: 
        """
        if self.isAjax:
            self.write(json.dumps(kwargs))
            return
        if kwargs.get("href"):
            self.redirect(kwargs.get("href"))
            return
        # self.write(json.dumps(kwargs))
        self.write_error(403, msg=kwargs.get('msg'))
        return
